<template>
  <div>
    <!-- <div v-for="(items,indexs) in arr" :key="indexs"> -->
    <!-- class="dialog-wrap"
      modal-class="modal-wrap"
      :modal="false"
      :lock-scroll="false" draggable -->
    <el-dialog :title="title" align-center v-model="open" :close-on-click-modal="false" width="800px"
      :before-close="cancel">
      <el-form ref="actionDialog" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="命令" prop="deviceAction">
              <el-select v-model="form.deviceAction" placeholder="请选择命令" clearable style="width:300px;">
                <el-option v-for="(item,index) in device_action" :key="item.command" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="设备" prop="device">
              <el-input type="textarea" :rows="4" v-model="form.device" placeholder="" />
              <div style="display: block;width: 100%;" class="mt10">
                <span style="font-weight: bold !important;">
                  已选择设备:
                </span>
                <span>
                  {{form.deviceName}}
                </span>
              </div>
              <div class="mt10" style="display: block !important;">
                <el-button type="primary" @click="handleSelectProject">选择项目</el-button>
                <el-button type="primary" @click="handleDeviceGroup">选择分组</el-button>
                <el-button type="primary" @click="handleDevice">选择设备</el-button>
              </div>

            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.deviceAction == 5 || form.deviceAction == 6">
            <el-form-item :label="form.deviceAction == 5 ? '启动时间' : '停止时间'" prop="dataTime">
              <el-date-picker v-model="form.dataTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                :placeholder="form.deviceAction == 5 ? '请选择启动时间' : '请选择停止时间'" />
            </el-form-item>
          </el-col>
          <!-- 1召唤设备 true，2安装软件（一个附加内容），3重启手机 true，4重启脚本 true，5定时启动（时间选择器带时分秒），6定时停止（时间选择器带时分秒），7自定义任务（两个附加内容），8开启自动化 true，9执行Shell命令（一个附加内容） -->
          <el-col :span="24" v-if="form.deviceAction == 2 || form.deviceAction == 7 || form.deviceAction == 9">
            <el-form-item label="附加内容" prop="content">
              <el-input type="textarea" :rows="4" v-model="form.content" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.deviceAction == 7">
            <el-form-item label="操作">
              <el-radio-group v-model="form.actionRadio">
                <el-radio label="contentTwo">附加内容2</el-radio>
                <el-radio label="true">true</el-radio>
                <el-radio label="false">false</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.deviceAction == 7 && form.actionRadio == 'contentTwo' ">
            <el-form-item label="附加内容2" prop="contentTwo">
              <el-input type="textarea" :disabled="form.actionRadio != 'contentTwo'" :rows="4" v-model="form.contentTwo"
                placeholder="" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog class="dialog-wrap2" :title="TwoTitle" align-center v-model="openTwo" v-if="openTwo" width="800px"
      :before-close="cancelTwo">
      <div>
        <div class="mb10" style="display: flex;align-items: center;">
          <el-form label-width="100px">
            <el-form-item :label="TwoTitle == '选择项目' ? '项目名称' : TwoTitle == '选择设备分组' ? '设备分组名' : '设备名字' ">
              <el-input v-model="selectName" placeholder="" style="width: 300px;" clearable />
              <el-button type="primary" class="ml10" @click="handleSelectTable">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <Table ref="pageTableRef" :table-data="tableData" :border="true" size="small" :loading="loading"
          :columns="columns" :is-pagination="false" :selection="true" :show-index="true" height="300"
          @handleSelectionChange="handleSelectionChange">
          <!-- <template #isScriptRunning="scope">
            <el-tag v-if="scope.row.isScriptRunning" type="success">启动</el-tag>
            <el-tag v-else type="info">未启动</el-tag>
          </template> -->
        </Table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitSelect">确 定</el-button>
          <el-button @click="cancelTwo">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- </div> -->
  </div>
</template>

<script setup name="actionDialog">
  import { getSelectTypeList, updateDevices, getDevicesActionMessage } from "@/api/deviceManage/index.js";
  const { proxy } = getCurrentInstance();
  const emit = defineEmits(["cancel"]);
  const { device_action } = proxy.useDict('device_action'); // 设备操作
  const open = ref(false);
  const openTwo = ref(false);
  const title = ref("发送命令");
  const TwoTitle = ref("选择项目");
  const buttonLoading = ref(false);
  const tableData = ref([]);
  const loading = ref(false);
  const columns = ref([]);
  const project = ref('');
  const selectData = ref('');
  const selectName = ref('');
  const data = reactive({
    form: {
      deviceAction: '', // 命令
      device: '', // 设备
      deviceName: '',
      dataTime: '', // 时间
      content: '', // 附加内容
      actionRadio: '', // 操作
      contentTwo: '', // 附加内容2
      selectDate: ''
    },
    queryParams: {
      pageNum: 1,
      pageSize: 100,
    },
    rules: {
      device: [
        { required: true, message: "请选择设备", trigger: "change" }
      ],
      content: [
        { required: true, message: "请输入附加内容", trigger: "blur" }
      ],
      actionRadio: [
        { required: true, message: "操作不能为空", trigger: "blur" }
      ],
      contentTwo: [
        { required: true, message: "请输入附加内容2", trigger: "blur" }
      ],
    }
  });
  const { queryParams, form, rules } = toRefs(data);
  function getCurrentDate() {
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); // 注意月份从0开始
    var yyyy = today.getFullYear();
    return `${yyyy}-${mm}-${dd}`;
  }
  function submitSelect() {
    if (selectData.value.length) {
      // console.log(selectData.value, 'ABCDEFG-submitSelect');
      // console.log(selectData.value.length, 'ABCDEFG-submitSelect-length');
      // console.log(selectData.value.map(item => item.id), 'ABCDEFG-submitSelect-id');
      // console.log(selectData.value.map(item => item.name), 'ABCDEFG-submitSelect-name');
      form.value.device = selectData.value.map(item => item.id).join();
      form.value.deviceName = selectData.value.map(item => item.name).join();
      openTwo.value = false;
    } else {
      openTwo.value = false;
    }
    // form.value.device = selectData.value;
    // openTwo.value = false;
  }
  function handleSelectTable(row) {
    if (TwoTitle.value == '选择项目') {
      getSelectTypeList({
        type: 'project',
        project: project.value,
        selectDate: form.value.selectDate,
        name: selectName.value
      }).then(response => {
        if (response.length) {
          response.forEach(element => {
            if (element.deviceIdList && element.deviceIdList.length) {
              element.deviceIdString = element.deviceIdList.map(item => {
                return {
                  id: item.id,
                  name: item.name
                };
              });
            } else {
              element.deviceIdString = [];
            }
          });
        }
        // console.log(response, 'ABCDEFG-handleSelectProject');
        tableData.value = response || [];
      });
    }

    if (TwoTitle.value == '选择项目') {
      getSelectTypeList({
        type: 'deviceGroup',
        project: project.value,
        selectDate: form.value.selectDate,
        name: selectName.value
      }).then(response => {
        if (response.length) {
          response.forEach(element => {
            if (element.deviceIdList && element.deviceIdList.length) {
              element.deviceIdString = element.deviceIdList.map(item => {
                return {
                  id: item.id,
                  name: item.name
                };
              });
            } else {
              element.deviceIdString = [];
            }
          });
        }
        // console.log(response, 'ABCDEFG-handleSelectProject');
        tableData.value = response || [];
      });
    }
    if (TwoTitle.value == '选择设备') {
      if (selectName.value) {
        tableData.value = tableData.value.filter(item => item.name.toLowerCase().includes(selectName.value.toLowerCase()));
      } else {
        getSelectTypeList({
          type: 'project',
          project: project.value,
          selectDate: form.value.selectDate
        }).then(response => {
          tableData.value = response.deviceIdList || [];
          // console.log(response, 'handleDevice');
          if (response.length) {
            response.forEach(element => {
              if (element.name == project.value) {
                tableData.value = element.deviceIdList || [];
              }
            });
          }
        });
      }
    }
  }
  function handleSelectProject() {
    TwoTitle.value = '选择项目';
    columns.value = [
      {
        prop: 'name',
        label: '项目',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'userName',
        label: '所属',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
    ];
    getSelectTypeList({
      type: 'project',
      project: project.value,
      selectDate: form.value.selectDate,
      name: selectName.value
    }).then(response => {
      if (response.length) {
        response.forEach(element => {
          if (element.deviceIdList && element.deviceIdList.length) {
            element.deviceIdString = element.deviceIdList.map(item => {
              return {
                id: item.id,
                name: item.name
              };
            });
          } else {
            element.deviceIdString = [];
          }
        });
      }
      // console.log(response, 'ABCDEFG-handleSelectProject');
      tableData.value = response || [];
      openTwo.value = true;
    });
  }
  function handleDeviceGroup() {
    TwoTitle.value = '选择设备分组';
    columns.value = [
      {
        prop: 'name',
        label: '分组',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'userName',
        label: '所属',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
    ];
    getSelectTypeList({
      type: 'deviceGroup',
      project: project.value,
      selectDate: form.value.selectDate
    }).then(response => {
      if (response.length) {
        response.forEach(element => {
          if (element.deviceIdList && element.deviceIdList.length) {
            element.deviceIdString = element.deviceIdList.map(item => {
              return {
                id: item.id,
                name: item.name
              };
            });
          } else {
            element.deviceIdString = [];
          }
        });
      }
      // console.log(response, 'ABCDEFG-handleSelectProject');
      tableData.value = response || [];
      openTwo.value = true;
    });
  }
  function handleDevice() {
    TwoTitle.value = '选择设备';
    columns.value = [
      {
        prop: 'id',
        label: '设备ID',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'name',
        label: '设备',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'userName',
        label: '所属',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
    ];
    getSelectTypeList({
      type: 'project',
      project: project.value,
      selectDate: form.value.selectDate
    }).then(response => {
      tableData.value = response.deviceIdList || [];
      // console.log(response, 'handleDevice');
      if (response.length) {
        response.forEach(element => {
          if (element.name == project.value) {
            tableData.value = element.deviceIdList || [];
          }
          // console.log(response, 'handleDevice');
        });
      }
      openTwo.value = true;
    });
  }
  function cancelTwo() {
    columns.value = [];
    tableData.value = [];
    selectName.value = '';
    openTwo.value = false;
  }
  function openDialog(row) {
    // console.log(row, 'ABCDEFG-row');
    form.value.deviceAction = row.deviceAction || '';
    form.value.selectDate = row.selectDate || '';
    project.value = row.project || '';
    open.value = true;
    // reset();
  }
  // 取消按钮
  function cancel() {
    proxy.resetForm("actionDialog");
    emit("cancel", false);
    open.value = false;
    // reset();
  }
  function findLabel(dict, dictValue) {
    let dictItem = dict.find(item => item.value == dictValue);
    return dictItem ? dictItem.label : '';
  }
  /** 提交按钮 */
  function submitForm() {
    // console.log(form.value, 'ABCDEFG-submitForm');
    proxy.$refs["actionDialog"].validate(valid => {
      if (valid) {
        buttonLoading.value = true;
        let params = [];
        // {
        //   deviceIdList: form.value.device.split(','),
        //   actionMessage: {}
        // };
        // {
        //   1"召唤设备" : true;
        //   2"安装软件" : 123;
        //   3"重启手机" : true;
        //   4"重启脚本" : true;
        //   5"定时启动" : '2019-08-08 12:00:00';
        //   6"定时停止" : '2019-08-08 12:00:00';
        //   7"自定义任务" : { '123'：'附加内容2'; }
        //   8"开启自动化" : true;
        //   9"执行Shell命令" : 123;
        //   10"开始脚本" : true;
        //   11"立即停止" : true;
        //   12"任务停止" : true;
        //   13"继续脚本" : true;
        //   14"暂停脚本" : true;
        //   15"亮屏" : true;
        //   16"熄屏" : true;
        // }
        // console.log(form.value.device, 'ABCDEFG-device');
        // console.log(form.value.deviceAction, 'ABCDEFG-form.value.deviceAction');
        getDevicesActionMessage({ deviceIdList: form.value.device.split(',') }).then(response => {
          // console.log(response, 'ABCDEFG-getDevicesActionMessage');
          let selectList = response.data || [];
          if (selectList.length) {
            let paramsList = selectList.map(item => {
              return {
                actionMessage: item.actionMessage ? JSON.parse(item.actionMessage) : {},
                deviceId: item.deviceId,
              };
            });
            // console.log(paramsList, 'ABCDEFG-paramsList');
            if (paramsList.length) {
              paramsList.forEach((item) => {
                switch (form.value.deviceAction) {
                  //               form: {
                  //   deviceAction: '', // 命令
                  //   device: '', // 设备
                  //   content: '', // 附加内容
                  //   actionRadio: '', // 操作
                  //   contentTwo: '', // 附加内容2
                  // },
                  case '1':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '2':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = form.value.content;
                    break;
                  case '3':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '4':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '5':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = form.value.dataTime;
                    break;
                  case '6':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = form.value.dataTime;
                    break;
                  case '7':
                    let obj = {};
                    obj[form.value.content] = form.value.actionRadio == 'contentTwo' ? form.value.contentTwo : form.value.actionRadio;
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = obj;
                    break;
                  case '8':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '9':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = form.value.content;
                    break;
                  case '10':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '11':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '12':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '13':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '14':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '15':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                  case '16':
                    item.actionMessage[findLabel(device_action.value, form.value.deviceAction)] = true;
                    break;
                }
                item.actionMessage = JSON.stringify(item.actionMessage);
              });
              updateDevices(paramsList).then(response => {
                buttonLoading.value = false;
                cancel();
                proxy.$modal.msgSuccess("发送成功");
              }).catch(e => {
                buttonLoading.value = false;
              });
            }
          }
        }).catch(e => {
        });

        // params.actionMessage = JSON.stringify(params.actionMessage);
        // console.log(params, 'ABCDEFG-params');


      }
    });
  }
  function handleSelectionChange(selection) {
    // console.log(selection, 'ABCDEFG-selection');
    // selection.value
    if (TwoTitle.value != '选择设备') {
      let ids = selection.map(item => item.deviceIdString);
      let mergedArray = [];
      if (ids.length) {
        ids.forEach(item => {
          mergedArray = [...mergedArray, ...item];
        });
      }
      // console.log(mergedArray, 'ABCDEFG-mergedArray');

      selectData.value = mergedArray.length ? mergedArray : [];
    } else {
      let idList = selection.map(item => {
        return {
          id: item.id,
          name: item.name,
        };
      });
      // console.log(idList, 'ABCDEFG-123');
      selectData.value = idList.length ? idList : [];
    }

  }
  defineExpose({
    openDialog
  });
</script>
<style lang="scss" scoped>
  /* :deep(.modal-wrap) {
    pointer-events: none !important;
    margin-top: 50%;
  }

  :deep() {
    .dialog-wrap {
      pointer-events: auto !important;
      margin-top: 15vh !important;
    }

    .dialog-wrap2 {
      margin-top: 20vh !important;
    }
  } */

  :deep() {
    .el-dialog {
      pointer-events: auto !important;
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -40%);
      max-height: calc(100% - 60px);
      max-width: calc(100% - 30px);
    }

    .el-dialog .el-dialog__body {
      flex: 1;
      overflow: auto;
    }
  }
</style>
